<?php
class ServiceController extends Zend_Controller_Action
{
	/**
	 *
	 * Index action will be redirected to the home page
	 *
	 *
	 */
	function indexAction()
	{
		$this->_redirect('service/listservice');
	}

	/**
	 * List service action
	 *
	 *
	 */
	function listserviceAction()
	{
		$this->view->title = "Manage services";
		$service = new Service();
		$this->view->services = $service->fetchAll();
	}

	/**
	 * Add service action
	 *
	 */
	function addserviceAction()
	{
		$this->view->title = "Add new service";

		$form = new ServiceForm();
		$this->view->form = $form;

		if($this->_request->isPost()){
			$formData = $this->_request->getPost();
			if($form->isValid($formData)){
				$service = new Service();
				$row = $service->createRow();
				$row->code = $form->getValue('codeServiceForm');
				$row->description = $form->getValue('descServiceForm');
				$row->save();
				$this->_redirect('service/listservice');
			} else {
				$form->populate($formData);
			}
		}
	}

	/**
	 * Delete service action
	 *
	 */
	function deleteserviceAction(){
		$this->view->title = "Delete service";
		$registry = Zend_Registry::getInstance();
		$translator = $registry->get('Zend_Translate');
		if($this->_request->isPost()){
			$id = (int)$this->_request->getPost('id');
			$del = $this->_request->getPost('del');
			if($del == $translator->translate("Yes") && $id > 0){
				$services = new Service();
				$where = 'id= ' . $id;
				$services->delete($where);
			}
			$this->_redirect('service/listservice');
		} else {
			$id = (int)$this->_request->getParam('id');
			if($id > 0){
				$services = new Service();
				$this->view->service = $services->fetchRow('id=' . $id);
			}
		}
	}

	/**
	 * Edit service action
	 */
	function editserviceAction(){
		$this->view->title = "Edit service";
		$registry = Zend_Registry::getInstance();
		$translator = $registry->get('Zend_Translate');

		// init service form
		$form = new ServiceForm();
		$this->view->form = $form;

		// check to see whether a post request(update)
		if($this->_request->isPost()){
			$formData = $this->_request->getPost();
			if($form->isValid($formData)){
				$id = (int)$form->getValue('id');
				$services = new Service();
				$row = $services->fetchRow("id=" . $id);
				$row->code = $form->getValue('codeServiceForm');
				$row->description = $form->getValue('descServiceForm');
				$row->save();
				$this->_redirect('service/listservice');
			} else {
				$form->populate($formData);
			}
		} else { // not a post request(show)
			$id = (int)$this->_request->getParam('id');
			if($id > 0){
				$services = new Service();
				// fetch the required service
				$service = $services->fetchRow('id=' . $id);

				// populate the form
				$form->getElement('id')->setValue($id);
				$form->getElement('codeServiceForm')->setValue($service->code);
				$form->getElement('descServiceForm')->setValue($service->description);
				$form->getElement('submit')->setValue($translator->translate('Edit'));
				$form->getElement('submit')->setLabel('');

			} else {
				$this->_redirect('service/listservice');
			}
		}
	}

	/**
	 * Assign service action
	 */
	function assignagentcodeAction(){
		$this->view->title = "Assign service";
		$form = new UserServiceForm();
		$this->view->form = $form ;

		if($this->_request->isPost()){
			$formData = $this->_request->getPost();
			// attach agent service code validator to the agentCodeAgentServiceForm field
			$agentcode_validator = new Zend_Validate_NewAgentCode();
			$agentcode_validator->setServiceId($this->_request->getParam('serviceIdAgentServiceForm'));
			$agentcode_validator->setAgentId($this->_request->getParam('agentIdAgentServiceForm'));
			$form->getElement('agentCodeAgentServiceForm')->addValidator($agentcode_validator);
			if($form->isValid($formData)){
				$service = new UserService();
				$row = $service->createRow();
				$row->agent_id = $form->getValue('agentIdAgentServiceForm');
				$row->service_id = $form->getValue('serviceIdAgentServiceForm');
				$row->agent_service_code = $form->getValue('agentCodeAgentServiceForm');
				$row->save();
				$this->_redirect('service/listagentbyservice/service_id/' . $row->service_id);
			} else {
				$form->populate($formData);
			}
		}else{
			$service_id = $this->_request->getParam('service_id');
			if(isset($service_id)){
				$form->getElement('serviceIdAgentServiceForm')->setValue($service_id);
			}
		}
	}

	/**
	 * List agent by service action
	 */
	 function listagentbyserviceAction(){

	 	$this->view->title = "Assigned agents";
	 	$registry = Zend_Registry::getInstance();
		$access_levels = $registry->get('access_level_config');
		$paging_config = $registry->get('paging_config');
		// init users database object
		$service_id = $this->_request->getParam('service_id');
		$userservices = new UserService();
		// fetch rows to show
		$page = $this->_getParam('page',1);
		$select = $userservices->getAdapter()->select()
									->from(array('us' => 'vmg_user_service'), array('id', 'agent_service_code'))
						            ->joinleft(array('u' => 'vmg_user'),
						                        'us.agent_id = u.id', array('u.name as agent_name'))
						            ->joinleft(array('s' => 'vmg_service'), 'us.service_id = s.id', array('s.code as service_code'))
						            ->where('us.service_id = ' . $service_id);

		$rows = $userservices->getAdapter()->fetchAll($select);

		// init paginator object
		$paginator = Zend_Paginator::factory($rows);
		$paginator->setItemCountPerPage($paging_config->items);
		$paginator->setCurrentPageNumber($page);

		// set paginator
		$this->view->paginator=$paginator;
	 }

	 /**
	  * delete agent code action
	  */
	 function deleteagentcodeAction(){
	 	// Page title
	 	$this->view->title = "Delete agent code";
	 	$registry = Zend_Registry::getInstance();
	 	$translator = $registry->get('Zend_Translate');

	 	// Process request
	 	if($this->_request->isPost()){
			$id = (int)$this->_request->getPost('id');
			$service_id = (int)$this->_request->getPost('service_id');
			$del = $this->_request->getPost('del');
			if($del == $translator->translate("Yes") && $id > 0){
				$userservices = new UserService();
				$where = 'id= ' . $id;
				$userservices->delete($where);
			}
			$this->_redirect('service/listagentbyservice/service_id/' . $service_id);
		} else {
			$id = (int)$this->_request->getParam('id');
			if($id > 0){
				$userservices = new UserService();
				$this->view->userservice = $userservices->fetchRow('id=' . $id);
			}
		}

	 }

	 /**
	  * edit agent code action
	  */
	 function editagentcodeAction(){
	 	// Page title
	 	$this->view->title = "Edit agent code";
	 	$registry = Zend_Registry::getInstance();
	 	$translator = $registry->get('Zend_Translate');

	    // init service form
		$form = new UserServiceForm();
		$this->view->form = $form;

		$form->removeElement('serviceIdAgentServiceForm');
		$form->addElement(new Zend_Form_Element_Hidden('serviceIdAgentServiceForm'));
		$form->removeElement('agentIdAgentServiceForm');
				$form->addElement(new Zend_Form_Element_Hidden('agentIdAgentServiceForm'));

		// check to see whether a post request(update)
		if($this->_request->isPost()){
			$id = (int)$this->_request->getParam('id');
			$userservices = new UserService();
			$row = $userservices->fetchRow("id=" . $id);
			if($this->_request->getParam('agentCodeAgentServiceForm') != $row->agent_service_code){
				// attach agent service code validator to the agentCodeAgentServiceForm field
				$agentcode_validator = new Zend_Validate_NewAgentCode();
				$form->getElement('agentCodeAgentServiceForm')->addValidator($agentcode_validator);
			}
			$formData = $this->_request->getPost();
			if($form->isValid($formData)){
				if(($row->service_id == $form->getValue('serviceIdAgentServiceForm')) && ($row->agent_id == $form->getValue('agentIdAgentServiceForm'))){
					$row->agent_service_code = $form->getValue('agentCodeAgentServiceForm');
					$row->save();
				}
				$this->_redirect('service/listagentbyservice/service_id/' . $row->service_id);
			} else {
				$form->populate($formData);
				$form->getElement('submitAgentServiceForm')->setValue($translator->translate('Edit'));
				$form->getElement('backAgentServiceForm')->setValue($translator->translate('Back'));
			}
		} else { // not a post request(show)
			$id = (int)$this->_request->getParam('id');
			if($id > 0){
				$userservices = new UserService();
				// fetch the required service
				$userservice = $userservices->fetchRow('id=' . $id);
				// populate the form
				$form->getElement('serviceIdAgentServiceForm')->setValue($userservice->service_id);

				$form->getElement('agentIdAgentServiceForm')->setValue($userservice->agent_id);
				$form->getElement('agentCodeAgentServiceForm')->setValue($userservice->agent_service_code);
				$form->getElement('submitAgentServiceForm')->setValue($translator->translate('Edit'));
				$form->getElement('backAgentServiceForm')->setValue($translator->translate('Back'));
			} else {
				$this->_redirect('service/listagentbyservice/service_id/' . $row->service_id);
			}
		}
	 }
}

/**
 * This validator will be use to ensure that we won't have duplicated agent_code in the database
 * @author nhchung
 *
 */
class Zend_Validate_NewAgentCode extends Zend_Validate_Abstract
{
	private $_agent_id = 0;
	private $_service_id = 0;
	const DUP_CODE_MESSAGE = 'duplicated_code';
	const DUP_KEY_MESSAGE = 'duplicated_key';
	protected $_messageTemplates = array(
        self::DUP_CODE_MESSAGE => "The agent service code '%value%' is used",
        self::DUP_KEY_MESSAGE => "This agent has been assigned a code for the service '%value%'"
    );

    public function setServiceId($service_id){
    	$this->_service_id = $service_id;
    }

    public function setAgentId($agent_id){
    	$this->_agent_id = $agent_id;
    }

    public function isValid($value){
    	$this->_setValue($value);
    	$userservices = new UserService();

    	// Check to ensure this code is not duplicated
    	$select = $userservices->select()->from($userservices, array('agent_service_code'))
       			->where('agent_service_code=?', $value);
		$rows = $userservices->fetchAll($select);
    	if(count($rows) > 0){
    		$this->_error(self::DUP_CODE_MESSAGE);
    		return false;
    	}

    	// Check to ensure the pair of service_id and agent_id is not duplicated
    	if(isset($this->_agent_id) && isset($this->_service_id)){
    		$select = $userservices->select()->from($userservices, array('agent_service_code'))
       			->where('agent_id=?', $this->_agent_id)
       			->where('service_id=?', $this->_service_id);

       		$row = $userservices->fetchRow($select);

       		if(isset($row['agent_service_code'])){
       			$this->_error(self::DUP_KEY_MESSAGE, $row['agent_service_code']);
    			return false;
       		}
    	}
    	return true;
    }
}
